import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import Header from "../component/Header.jsx";
import Line from "../component/Line.jsx";
import { Button, Flex, Typography } from "antd";
import e from "../cssForPages/ExtendedFeedback.module.css";
import Buttons from "../component/Buttons.jsx";
import contentImg from "../img/image 1.svg";
import ButtonsExtended from "../component/ButtonsExtended.jsx";

export default function ExtendedFeedback() {
  const navigate = useNavigate();
  const [responses, setResponses] = useState([]);
  const [requiredAnswers, setRequiredAnswers] = useState({});
  const [isFormComplete, setIsFormComplete] = useState(false);

  const initialButtonState = {
    1: null,
    2: null,
    3: null,
    4: null,
    5: null,
    6: null,
  };
  const [buttonState, setButtonState] = useState(initialButtonState);

  useEffect(() => {
    const storedResponses = JSON.parse(localStorage.getItem("responses")) || [];
    const completed = localStorage.getItem("completed") === "true";

    if (completed) {
      navigate("/survey-completed");
    } else {
      setResponses(storedResponses);
      const required = storedResponses.reduce((acc, response) => {
        acc[response.questionID] = response.responseID;
        return acc;
      }, {});
      setRequiredAnswers(required);
      const storedButtonState =
        JSON.parse(localStorage.getItem("buttonState")) || initialButtonState;
      setButtonState(storedButtonState);
    }
  }, [navigate]);

  useEffect(() => {
    const requiredQuestionIDs = [1, 2, 3, 4, 5, 6];
    const allRequiredAnswered = requiredQuestionIDs.every(
      (id) => requiredAnswers[id],
    );
    setIsFormComplete(allRequiredAnswered);
  }, [requiredAnswers]);

  const handleAnswer = (questionID, responseID) => {
    const updatedResponses = responses.filter(
      (response) => response.questionID !== questionID,
    );
    updatedResponses.push({ questionID, responseID });
    setResponses(updatedResponses);
    localStorage.setItem("responses", JSON.stringify(updatedResponses));
    setRequiredAnswers((prev) => ({ ...prev, [questionID]: responseID }));

    const updatedButtonState = { ...buttonState, [questionID]: responseID };
    setButtonState(updatedButtonState);
    localStorage.setItem("buttonState", JSON.stringify(updatedButtonState));
  };

  const handleSubmit = () => {
    if (isFormComplete) {
      const selectedValue = localStorage.getItem("selectedValue");
      console.log("Первый выбранный рейтинг:", selectedValue);
      console.log("Ответы на дополнительные вопросы:", responses);
      localStorage.setItem("completed", "true");
      navigate("/thank-you");
    }
  };

  return (
    <>
      <Header />
      <Line />
      <Flex className={e.allContent} justify={"space-between"} align={"center"}>
        <Flex vertical className={e.inputList}>
          <Typography.Text className={e.inputText}>
            Пожалуйста, ответьте на дополнительные вопросы.
          </Typography.Text>
          <Flex vertical className={e.items}>
            <Typography.Text className={e.questionText}>
              1. Как быстро вы получили ответ от клиентского сервиса RUTUBE? *
            </Typography.Text>
            <Flex vertical>
              <button
                type="button"
                className={`${e.buttonsInput} ${buttonState[1] === 1 ? e.activeButton : ""}`}
                onClick={() => handleAnswer(1, 1)}
              >
                Быстрее, чем ожидал
              </button>
              <button
                type="button"
                className={`${e.buttonsInput} ${buttonState[1] === 2 ? e.activeButton : ""}`}
                onClick={() => handleAnswer(1, 2)}
              >
                Как и ожидал
              </button>
              <button
                type="button"
                className={`${e.buttonsInput} ${buttonState[1] === 3 ? e.activeButton : ""}`}
                onClick={() => handleAnswer(1, 3)}
              >
                Медленнее, чем ожидал
              </button>
            </Flex>
            <Typography.Text className={e.questionText}>
              2. Клиентский сервис RUTUBE помог в решении проблемы? *
            </Typography.Text>
            <Flex
              justify="space-around"
              className={e.buttons}
              style={{ marginTop: "10px", width: "250px" }}
            >
              <ButtonsExtended
                number={5}
                handleClick={(value) => handleAnswer(2, value)}
                selectedValue={buttonState[2]}
              />
            </Flex>
            <Typography.Text className={e.questionText}>
              3. Специалист RUTUBE хорошо изъяснялся и владел языком? *
            </Typography.Text>
            <Flex
              justify="space-around"
              className={e.buttons}
              style={{ marginTop: "10px", width: "250px" }}
            >
              <ButtonsExtended
                number={5}
                handleClick={(value) => handleAnswer(3, value)}
                selectedValue={buttonState[3]}
              />
            </Flex>
            <Typography.Text className={e.questionText}>
              4. Специалист RUTUBE был отзывчив? *
            </Typography.Text>
            <Flex
              justify="space-around"
              className={e.buttons}
              style={{ marginTop: "10px", width: "250px" }}
            >
              <ButtonsExtended
                number={5}
                handleClick={(value) => handleAnswer(4, value)}
                selectedValue={buttonState[4]}
              />
            </Flex>
            <Typography.Text className={e.questionText}>
              5. Специалист RUTUBE был компетентен? *
            </Typography.Text>
            <Flex
              justify="space-around"
              className={e.buttons}
              style={{ marginTop: "10px", width: "250px" }}
            >
              <ButtonsExtended
                number={5}
                handleClick={(value) => handleAnswer(5, value)}
                selectedValue={buttonState[5]}
              />
            </Flex>
            <Typography.Text className={e.questionText}>
              6. Какова вероятность того, что вы порекомендуете RUTUBE коллеге
              или другу? *
            </Typography.Text>
            <Flex
              justify="space-around"
              className={e.buttons}
              style={{ marginTop: "10px" }}
            >
              <Buttons
                number={11}
                handleClick={(value) => handleAnswer(6, value)}
                selectedValue={buttonState[6]}
              />
            </Flex>
            <Button
              className={e.btnSend}
              onClick={handleSubmit}
              disabled={!isFormComplete}
            >
              Отправить ответы
            </Button>
          </Flex>
        </Flex>
        <img src={contentImg} alt="" className={e.contentImg} />
      </Flex>
    </>
  );
}
